/**
 * The contents of this file are subject to the OpenMRS Public License
 * Version 1.0 (the "License"); you may not use this file except in
 * compliance with the License. You may obtain a copy of the License at
 * http://license.openmrs.org
 *
 * Software distributed under the License is distributed on an "AS IS"
 * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
 * License for the specific language governing rights and limitations
 * under the License.
 *
 * Copyright (C) OpenMRS, LLC.  All Rights Reserved.
 */
package org.openmrs.module.datalogging.handler.event;

import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.openmrs.module.datalogging.configuration.Event;
import org.openmrs.module.datalogging.filter.Filter;
import org.openmrs.module.datalogging.filter.FilterFactory;
import org.openmrs.module.datalogging.filter.FilterUtils;
import org.openmrs.util.OpenmrsUtil;

/**
 *
 */
public class ObsEventHandler extends OpenmrsEventHandler {
	
	private static final Log log = LogFactory.getLog(ObsEventHandler.class);
	
	/**
	 * @see org.openmrs.module.datalogging.handler.event.OpenmrsEventHandler#registerFilters()
	 */
	@Override
	protected void registerFilters() {
		registerFilter("concept");
		registerFilter("valueCoded");
	}
	
	/**
	 * @see org.openmrs.module.datalogging.handler.event.EventHandler#allow(org.openmrs.module.datalogging.configuration.Event,
	 *      java.lang.Object)
	 */
	@Override
	public boolean allow(Event event, Object object) {
		String eventFilters[] = StringUtils.split(event.getEventFilter(), FilterUtils.EXPRESSION_SEPARATOR);
		boolean allow = true;
		for (String eventFilter : eventFilters)
			allow = allow && allowEvent(eventFilter, object);
		return allow;
	}
	
	private boolean allowEvent(String eventFilter, Object object) {
		String filterKey = eventFilter.substring(0, eventFilter.indexOf(FilterUtils.KEY_SEPARATOR));
		if (supportFilter(filterKey)) {
			try {
				String filterValue = eventFilter.substring(eventFilter.indexOf(FilterUtils.KEY_SEPARATOR) + 1);
				
				Filter filterHandler = FilterFactory.getHandler(filterKey);
				String[] filterValues = StringUtils.split(filterValue, FilterUtils.VALUE_SEPARATOR);
				
				Object filteredProperty = PropertyUtils.getProperty(object, filterKey);
				for (String value : filterValues) {
					Object filter = filterHandler.getFilterValue(value);
					if (OpenmrsUtil.nullSafeEquals(filteredProperty, filter))
						return true;
				}
			} catch (Exception e) {
				log.error("Error generated", e);
			}
		}
		return false;
	}
	
}
